package com.xju.atpgs.service.Impl;

import com.xju.atpgs.entity.*;
import com.xju.atpgs.mapper.DictionaryMapper;
import com.xju.atpgs.mapper.QuestionMapper;
import com.xju.atpgs.mapper.UserMapper;
import com.xju.atpgs.service.DictionaryService;
import com.xju.atpgs.service.QuestionService;
import com.xju.atpgs.service.SectionService;
import com.xju.atpgs.service.UserService;
import com.xju.atpgs.utils.IDGenerator;
import com.xju.atpgs.utils.SecurityUserHelper;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private SectionService sectionService;

    @Autowired
    private UserService userService;

    @Override
    public void insert(Question question) {
        questionMapper.insert(question);
    }

    @Override
    public void uploadFile(MultipartFile file) {
        try {
            String filename=file.getOriginalFilename();
            String path= ClassUtils.getDefaultClassLoader().getResource("").getPath();
            XSSFWorkbook workbook=new XSSFWorkbook(new FileInputStream("D:/upload/file/"+filename));
            XSSFSheet sheet=workbook.getSheetAt(0);
            for (Row row:sheet){
                if (row.getRowNum()==0){
                    continue;
                }
                UploadQuestion uploadQuestion=new UploadQuestion();
                String content=row.getCell(0).getStringCellValue();
                String answer=row.getCell(1).getStringCellValue();
                String describe=row.getCell(2).getStringCellValue();
                String section=row.getCell(3).getStringCellValue();
                String type=row.getCell(4).getStringCellValue();
                String level=new String();
                Random random=new Random();
                DecimalFormat decimalFormat=new DecimalFormat("#0.00");
                double x=random.nextDouble();
                level=decimalFormat.format(x);
                int index=row.getRowNum()-1;
                uploadQuestion.setQuesContent("第"+index+"题"+content);
                uploadQuestion.setQuesAnswer(answer);
                uploadQuestion.setQuesDescribe(describe);
                uploadQuestion.setQuesLevel(level);
                uploadQuestion.setQuesSection(section);
                uploadQuestion.setQuesType(type);
                Question question=transformToQuestion(uploadQuestion);
                question.setQuesId(IDGenerator.getId());
                Date date=new Date();
                question.setQuesCreateTime(date);
                question.setQuesStatus(dictionaryService.findByValue("可用").getDicId());
                UserDetails user= (UserDetails) SecurityUserHelper.getCurrentUser();
                question.setQuesCreator(userService.findByEmail(user.getUsername()).getUserId());
                insert(question);
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Question transformToQuestion(UploadQuestion uploadQuestion) {
        Question question=new Question();
        question.setQuesContent(uploadQuestion.getQuesContent());
        question.setQuesAnswer(uploadQuestion.getQuesAnswer());
        question.setQuesDescribe(uploadQuestion.getQuesDescribe());
        Section section=sectionService.findByName(uploadQuestion.getQuesSection());
        question.setQuesSection(section.getSecId());
        question.setQuesLevel(uploadQuestion.getQuesLevel());
        Dictionary dictionary=dictionaryService.findByValue(uploadQuestion.getQuesType());
        question.setQuesType(dictionary.getDicId());
        return question;
    }

    @Override
    public List<Question> findAll() {
        QuestionExample questionExample=new QuestionExample();
        questionExample.createCriteria().andQuesIdIsNotNull();
        List<Question> questionList=questionMapper.selectByExampleWithBLOBs(questionExample);
        return questionList;
    }

    @Override
    public Question modifyRequest(String id) {
        Question question=questionMapper.selectByPrimaryKey(id);
        return question;
    }

    @Override
    public ResultQuestion questionDetail(String id, String section, String type, String level) {
        Question question=questionMapper.selectByPrimaryKey(id);
        ResultQuestion resultQuestion=transformToResultQuestion(question);
        resultQuestion.setSelectedSection(section);
        resultQuestion.setSelectedLevel(level);
        resultQuestion.setSelectedType(type);
        return resultQuestion;
    }

    @Override
    public ResultQuestion transformToResultQuestion(Question question){
        ResultQuestion resultQuestion=new ResultQuestion();
        String creatorName=userService.findById(question.getQuesCreator()).getUserName();
        String sectionName=sectionService.findById(question.getQuesSection()).getSecName();
//        String modifyName=userService.findById(question.getQuesLastModifyUser()).getUserName();
        String typeName=dictionaryService.findById(question.getQuesType()).getDicValue();
        String levelName=dictionaryService.findById(question.getQuesLevel()).getDicValue();
        String statusName=dictionaryService.findById(question.getQuesLevel()).getDicValue();
        resultQuestion.setQuesCreatorName(creatorName);
        resultQuestion.setQuesSectionName(sectionName);
        resultQuestion.setQuesLevelName(levelName);
        resultQuestion.setQuesStatusName(statusName);
        resultQuestion.setQuesTypeName(typeName);
        resultQuestion.setQuestion(question);
        return resultQuestion;
    }

    @Override
    public ResultQuestionManage manage(String section, String type, String level) {
        ResultQuestionManage resultQuestionManage=new ResultQuestionManage();
        List<Dictionary> types=dictionaryService.searchByType("试题类型");
        List<Section> sections=sectionService.findAll();
        List<Dictionary> levels=dictionaryService.searchByType("试题难度");
        QuestionExample questionExample=new QuestionExample();
        QuestionExample.Criteria criteria=questionExample.createCriteria();
        if(section.equals("null")&&type.equals("null")&&level.equals("null")){
            criteria.andQuesIdIsNotNull();
        }else {
            if (!section.equals("null")){
                criteria.andQuesSectionEqualTo(section);
            }
            if(!type.equals("null")){
                criteria.andQuesTypeEqualTo(type);
            }
            if(!level.equals("null")){
                List<Dictionary> dictionaryList=dictionaryService.searchByType("试题难度");
                for(Dictionary dictionary:dictionaryList){
                    if(level.equals(dictionary.getDicId())){
                        switch (dictionary.getDicValue()){
                            case "易":
                                criteria.andQuesLevelGreaterThan(0.00);
                                criteria.andQuesLevelLessThan(0.20);break;
                            case "偏易":
                                criteria.andQuesLevelGreaterThan(0.20);
                                criteria.andQuesLevelLessThan(0.40);break;
                            case "中等":
                                criteria.andQuesLevelGreaterThan(0.40);
                                criteria.andQuesLevelLessThan(0.60);break;
                            case "偏难":
                                criteria.andQuesLevelGreaterThan(0.60);
                                criteria.andQuesLevelLessThan(0.80);break;
                            case "难":
                                criteria.andQuesLevelGreaterThan(0.80);
                                criteria.andQuesLevelLessThan(1.00);break;
                        }
                    }
                }
            }
        }
        List<Question> questionList=questionMapper.selectByExampleWithBLOBs(questionExample);
        resultQuestionManage.setSectionList(sections);
        resultQuestionManage.setTypeList(types);
        resultQuestionManage.setLevelList(levels);
        resultQuestionManage.setQuestionList(questionList);
        resultQuestionManage.setSectionSelected(section);
        resultQuestionManage.setLevelSelected(level);
        resultQuestionManage.setTypeSelected(type);
        return resultQuestionManage;
    }

    @Override
    public ResultQuestion pageDetail(String id, String section, String type, String level,String page) {
        QuestionExample questionExample=new QuestionExample();
        QuestionExample.Criteria criteria=questionExample.createCriteria();
        if(section.equals("null")&&type.equals("null")&&level.equals("null")){
            criteria.andQuesIdIsNotNull();
        }else {
            if (!section.equals("null")){
                criteria.andQuesSectionEqualTo(section);
            }
            if(!type.equals("null")){
                criteria.andQuesTypeEqualTo(type);
            }
            if(!level.equals("null")){
                criteria.andQuesLevelEqualTo(level);
            }
        }
        List<Question> questionList=questionMapper.selectByExampleWithBLOBs(questionExample);
        Question question1=questionMapper.selectByPrimaryKey(id);
        int index=questionList.indexOf(question1);
        int max=questionList.size();
        Question question2=new Question();
        if(index==0){
            if(page.equals("previous")||page.equals("current")){
                question2=questionList.get(index);
            }else {
                question2=questionList.get(index+1);
            }
        }else if(index==max-1){
            if(page.equals("next")||page.equals("curreent")){
                question2=questionList.get(index);
            }else{
                question2=questionList.get(index-1);
            }
        }else {
            if (page.equals("previous")){
                question2=questionList.get(index-1);
            }else if(page.equals("next")){
                question2=questionList.get(index+1);
            }else {
                question2=questionList.get(index);
            }
        }
        ResultQuestion resultQuestion=transformToResultQuestion(question2);
        resultQuestion.setSelectedType(type);
        resultQuestion.setSelectedLevel(level);
        resultQuestion.setSelectedType(type);
        return resultQuestion;
    }

    @Override
    public List<Question> findByType(String typename) {
        Dictionary dictionary=dictionaryService.findByValue(typename);
        QuestionExample questionExample=new QuestionExample();
        questionExample.createCriteria().andQuesTypeEqualTo(dictionary.getDicId());
        return questionMapper.selectByExampleWithBLOBs(questionExample);
    }

    @Override
    public Question findbyId(String id) {
        return questionMapper.selectByPrimaryKey(id);
    }
}
